#include <iostream>
#include <unicode/regex.h>
#include <unicode/ustream.h>
#include "UnicodeStringComparer.h"
#include "UnicodeError.h"

using namespace kc_sf;

// ----------------------------------------------------- //

UnicodeStringComparer::UnicodeStringComparer( const UnicodeString &ustring )
: u_string( ustring )
{
	u_matches = 0;
}

// ----------------------------------------------------- //

bool UnicodeStringComparer::matches( const UnicodeString &input )
{
	if( u_string.compareCodePointOrder( input ) == 0 )
	{
		++ u_matches;
		return true;
	}
	return false;
}

// ----------------------------------------------------- //

bool UnicodeStringComparer::contains( const UnicodeString &input )
{
	bool success = false;
	int32_t pos = 0;

	while( pos < input.length() && pos != -1 )
	{
		pos = u_string.indexOf( input, pos );
		if( pos == -1 )
			return success;

		++ u_matches;
		pos = pos + input.length();
		if( !success )
			success = true;
	}

	pos = u_string.indexOf( input, pos );
	return success;
}

// ----------------------------------------------------- //

bool UnicodeStringComparer::matchesRegex( const UnicodeString &input )
{
	UErrorCode status = U_ZERO_ERROR;

	RegexMatcher *matcher = new RegexMatcher( input, 0, status );
	if( U_FAILURE( status ) )
		throw UnicodeError( "Nie udało się zainicjalizować wyrażenia regularnego (UnicodeStringComparer::matchesRegex)" );

	matcher->reset( u_string );
	if( matcher->matches( status ) )
	{
		++ u_matches;
		delete matcher;
		return true;
	}

	delete matcher;
	return false;
}

// ----------------------------------------------------- //

bool UnicodeStringComparer::containsRegex( const UnicodeString &input )
{
	bool success = false;

	UErrorCode status = U_ZERO_ERROR;
	RegexMatcher *matcher = new RegexMatcher( input, 0, status );
	if( U_FAILURE( status ) )
		throw UnicodeError( "Nie udało się zainicjalizować wyrażenia regularnego (UnicodeStringComparer::containsRegex)" );

	matcher->reset( u_string );
	int64_t pos = 0;
	if( matcher->find( pos, status ) )
	{
	   pos = matcher->start( status );
	   ++ u_matches;
		if( !success )
			delete matcher;
			success = true;
	}

	delete matcher;
	return success;
}

// ----------------------------------------------------- //

int UnicodeStringComparer::matchesNr() const
{
	return u_matches;
}

